package com.riant.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @Classname TestRedirectController
 * @Description TODO
 * @Date 2022/5/1 10:34
 * @Created by 张斌
 */
@Controller
public class TestRedirectController {
    private final Logger logger = LoggerFactory.getLogger(TestController.class);

    @RequestMapping(path = {"/testRedirect1"}, method = RequestMethod.GET)
    public String test1() {
        this.logger.info("第一种通过重定向转发到fail.jsp");
        return "redirect:fail1";
    }

    @RequestMapping(path = {"/fail1"}, method = RequestMethod.GET)
    public String test5() {
        this.logger.info("forward转发到fail.jsp");
        return "forward:/WEB-INF/view/fail.jsp";
    }

    @RequestMapping(path = {"/testRedirect2"}, method = RequestMethod.GET)
    public String test2() {
        this.logger.info("重定向到WEB-INF/fail.jsp失败");
        //考虑到安全因素，无法直接访问WEB-INF下jsp，参考上面的通过forward转发，或者将jsp文件放在外面
        return "redirect:/WEB-INF/view/fail.jsp";
    }

    @RequestMapping(path = {"/testRedirect3"}, method = RequestMethod.GET)
    public ModelAndView test3() {
        ModelAndView modelAndView = new ModelAndView();
        this.logger.info("重定向到fail.jsp");
        //返回视图，进行重定向
        modelAndView.setViewName("redirect:fail1");
        return modelAndView;
    }

    @RequestMapping(path = {"/testRedirect4"}, method = RequestMethod.GET)
    public String test4() {
        this.logger.info("重定向到http://www.baidu.com");
        //访问外部资源
        return "redirect:http://www.baidu.com";
    }

    @RequestMapping(path = "/testRedirect6", method = RequestMethod.GET)
    public String test6(RedirectAttributes redirectAttributes) {
        logger.info("访问非/WEB-INF下jsp文件");
        //重定向带参数，渲染视图,只能在重定向的 “页面” （如jsp页面）中获取param参数值,原理就是放到session中，session在跳到页面后马上移除对象
        redirectAttributes.addFlashAttribute("msg","ddd");
        //在重定向链接地址追加传递的参数
        redirectAttributes.addAttribute("name","zhangsan");
        //重定向发起http://localhost:8081/springmvc_demo01/fail请求
        return "redirect:/static/view/fail.jsp";
    }
}
